package wiki.mdzz.learn_android.controllers

import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import wiki.mdzz.learn_android.data.Msg
import wiki.mdzz.learn_android.data.MsgRecyclerAdapter
import wiki.mdzz.learn_android.databinding.ActivityThirdBinding
import wiki.mdzz.learn_android.utils.BaseActivity

class ThirdActivity : BaseActivity() {
    private lateinit var binding: ActivityThirdBinding
    private var msgList = ArrayList<Msg>()
    private var adapter: MsgRecyclerAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityThirdBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val layoutManager = LinearLayoutManager(this)
        binding.messageRecyclerView.layoutManager = layoutManager
        initMsgList()
        adapter = MsgRecyclerAdapter(msgList)
        binding.messageRecyclerView.adapter = adapter
        binding.send.setOnClickListener {
            val content = binding.inputText.text.toString()
            if (content.isNotEmpty()) {
                val msg = Msg(content, Msg.SENT)
                msgList.add(msg)
                adapter?.notifyItemInserted(msgList.size - 1)
                binding.messageRecyclerView.scrollToPosition(msgList.size - 1)
                binding.inputText.setText("")
            }
        }
    }

    private fun initMsgList() {
        val msg1 = Msg("Hello guy1.", Msg.RECEIVED)
        msgList.add(msg1)
        val msg2 = Msg("Hello guy2.", Msg.SENT)
        msgList.add(msg2)
        val msg3 = Msg("Hello guy3.", Msg.RECEIVED)
        msgList.add(msg3)
    }
}